package com.bing.utils;

import org.apache.commons.codec.CharEncoding;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.net.ssl.SSLContext;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by kaibb on 2014/11/22.
 */
public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static CloseableHttpClient closeableHttpsClient;

    public static CloseableHttpClient createSSLClientDefault() {
        if (closeableHttpsClient != null) {
            return closeableHttpsClient;
        }
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain,
                                         String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            closeableHttpsClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            logger.error("KeyManagementException: ", e);
        } catch (NoSuchAlgorithmException e) {
            logger.error("NoSuchAlgorithmException: ", e);
        } catch (KeyStoreException e) {
            logger.error("KeyStoreException: ", e);
        }
        closeableHttpsClient = HttpClients.createDefault();
        return closeableHttpsClient;
    }


    public static <T> T get(String url, Class<? extends T> clazz) {
        HttpClient client = HttpUtils.createSSLClientDefault();
        logger.info("请求Url:{} ", url);
        HttpGet httpget = new HttpGet(url);
//执行get请求.
        HttpResponse responses = null;
        T result = null;
        try {
            responses = client.execute(httpget);
            if (responses.getStatusLine() != null && responses.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                HttpEntity entity = responses.getEntity();
                String out=EntityUtils.toString(entity, CharEncoding.UTF_8);
                logger.info("请求结果:{}", out);
                result = CommonUtils.GSON.fromJson(out, clazz);
            } else {
                logger.error("请求出错,状态:{}", responses.getStatusLine() == null ? "unknow" : responses.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            logger.error("请求出错,", e);
        }
        return result;
    }

    public static <T> T post(String url,String value, Class<? extends T> clazz) {
        HttpClient client = HttpUtils.createSSLClientDefault();
        logger.info("请求Url:{} ", url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity( new StringEntity(value,"UTF-8"));
//执行get请求.
        HttpResponse responses = null;
        T result = null;
        try {
            responses = client.execute(httpPost);
            if (responses.getStatusLine() != null && responses.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                HttpEntity entity = responses.getEntity();
                String out=EntityUtils.toString(entity, CharEncoding.UTF_8);
                logger.info("请求结果:{}", out);
                result = CommonUtils.GSON.fromJson(out, clazz);
            } else {
                logger.error("请求出错,状态:{}", responses.getStatusLine() == null ? "unknow" : responses.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            logger.error("请求出错,", e);
        }
        return result;
    }



    public static String get(String url) {
        HttpClient client = HttpClients.createDefault();
        logger.info("请求Url:{} ", url);
        HttpGet httpget = new HttpGet(url);
//执行get请求.
        HttpResponse responses = null;
        String result = null;
        try {
            responses = client.execute(httpget);
            if (responses.getStatusLine() != null && responses.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                HttpEntity entity = responses.getEntity();
                result=EntityUtils.toString(entity, CharEncoding.UTF_8);
                logger.info("请求结果:{}", result);
            } else {
                logger.error("请求出错,状态:{}", responses.getStatusLine() == null ? "unknow" : responses.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            logger.error("请求出错,", e);
        }
        return result;
    }
}
